<template>
  <el-row style=" height: 570px">
    <el-col :span="24">
      <h1>当前排号</h1>
      <template v-if="sns.length == 0">
        <el-empty description="暂无排号"/>
      </template>
      <template v-for="sn in sns">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <el-row :gutter="24">
              <el-col :span="20">
                排号时间：<span>{{ formatTime(sn.createTime) }}</span>
              </el-col>
              <el-col :span="4">
                <el-tag type="info" v-if="sn.snStatus == 1">未叫号</el-tag>
                <el-tag type="primary" v-if="sn.snStatus == 2">已叫号</el-tag>
                <el-tag type="warning" v-if="sn.snStatus == 3">过号</el-tag>
              </el-col>
            </el-row>
          </div>
          <p>患者姓名： {{ sn.patName }}</p>
          <template #footer>
            <el-button v-if="sn.snStatus == 1 || sn.snStatus == 3" type="primary" @click="callNum(sn)">叫号</el-button>
            <el-button v-if="sn.snStatus == 2" type="warning" @click="passNum(sn)">过号</el-button>
            <el-button v-if="sn.snStatus == 2" type="success" @click="showDialog(sn)">诊断</el-button>
          </template>
        </el-card>
      </template>
    </el-col>
  </el-row>
  <el-dialog title="诊断" v-model="dialogVisible" width="800">
    <el-form :model="mr" label-width="auto">
      <el-form-item label="患者：">
        <span style="font-size: 20px">{{ mr.patName }}</span>
      </el-form-item>
      <el-form-item label="诊断结果：">
        <el-input v-model="mr.mrDetail" type="textarea" :rows="5"></el-input>
      </el-form-item>
      <el-button type="primary" @click="prescribe()">去开药</el-button>
    </el-form>

    <template #footer>
      <el-button type="primary" @click="addMrAndRemoveSn()">诊断</el-button>
    </template>
  </el-dialog>

  <el-dialog title="开药方" v-model="preDrugDialogVisible" width="1000">
      <el-button type="primary" @click="showAddDrugDialog()">添加</el-button>
    <el-table :data="preDrugs" height="300px">
      <el-table-column label="药品名称" prop="drugName"/>
      <el-table-column label="数量" prop="drugNum"/>
      <el-table-column label="用量" prop="durgDetail"/>
    </el-table>
  </el-dialog>

  <el-dialog :title="drugTitle" v-model="drugDialogVisible" width="800">
    <el-form :model="preDrug" label-width="auto">
      <el-form-item label="药品名称：">
        <el-select v-model="preDrug.drugId" placeholder="请选择药品">
          <el-option v-for="drug in drugs" :key="drug.drugId" :label="drug.drugName" :value="drug.drugId"/>
        </el-select>
      </el-form-item>
      <el-form-item label="数量：">
        <el-input-number v-model="preDrug.drugNum" min="1"/>
      </el-form-item>
      <el-form-item label="用量：">
        <el-input v-model="preDrug.durgDetail"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drugDialogVisible = false">取消</el-button>
      <el-button type="primary" v-if="!isUpdate" @click="addPreDrug()">新增</el-button>
      <el-button type="primary" v-else @click="addPreDrug()">修改</el-button>
    </template>
  </el-dialog>
</template>

<script>
import {fetchAllSn, removeSn, renewSn} from "@/api/sn.js";
import jsCookie from "jscookie";
import {ElNotification} from "element-plus";
import {addMr} from "@/api/mr.js";
import {addPreDrug, fetchPreDrugList} from "@/api/preDrug.js";
import {addPre} from "@/api/pre.js";
import {addOp} from "@/api/op.js";
import {fetchAllDrug} from "@/api/drug.js";

export default {
  name: "callNum",
  data() {
    return {
      token: '',
      sns: [],
      dialogVisible: false,
      mr: {},
      preDrugDialogVisible: false,
      opId: 0,
      preId: 0,
      preDrugs: [],
      drugDialogVisible: false,
      drugs: [],
      preDrug: {},
      drugTitle: '',
      isUpdate: false,
    }
  },
  created() {
    this.token = jsCookie.get("token");
    this.fetchAllSn();
    this.fetchAllDrug()
  },
  methods: {
    async addPreDrug() {
      try {
        await addPreDrug(this.token, this.preDrug).then(async (response) => {
          this.fetchPreDrugList();
          this.drugDialogVisible = false;
          if (response.data.code == 200) {
            ElNotification({
              title: '成功',
              message: '添加药方成功',
              type: 'success'
            });
          } else {
            ElNotification({
              title: '失败',
              message: response.data.msg,
              type: 'error'
            })
          }
        })
      } catch (e) {
        ElNotification({
          title: '失败',
          message: '添加药方失败',
          type: 'error'
        })
      }
    },
    showAddDrugDialog() {
      this.preDrug = {
        preId: this.preId,
        drugNum: 1
      };
      this.drugTitle = '添加药方';
      this.isUpdate = false;
      this.drugDialogVisible = true;
    },
    async fetchPreDrugList() {
      await fetchPreDrugList(this.preId).then((response) => {
        this.preDrugs = response.data.data;
      })
    },
    async addPre() {
      let pre = {
        opId: this.opId
      };
      await addPre(pre).then((response) => {
        this.preId = response.data.data;
      });
    },
    async addOp() {
      let op = {
        opDetail: '购买药品',
        opMoney: 0,
        opDiscount: 0.8,
        patId: this.mr.patId
      };
      await addOp(null, op).then((response) => {
        this.opId = response.data.data;
      })
    },
    prescribe() {
      this.addOp().then(() => {
        this.addPre().then(() => {
          this.fetchPreDrugList().then(() => {
            this.preDrugDialogVisible = true;
          })
        })
      });
    },
    showDialog(sn) {
      this.mr = {
        patId: sn.patId,
        patName: sn.patName,
        docId: sn.docId,
        snId: sn.snId
      };
      this.dialogVisible = true;
    },
    async addMrAndRemoveSn() {
      try {
        this.mr.preId = this.preId;
        await addMr(this.token, this.mr).then(async (response) => {
          if (response.data.code == 200) {
            try {
              await removeSn(this.mr.snId).then(async (response) => {
                if (response.data.code == 200) {
                  ElNotification({
                    title: '成功！',
                    message: "诊断成功！",
                    type: 'success',
                  });
                  this.dialogVisible = false;
                  this.fetchAllSn();
                } else {
                  ElNotification({
                    title: '失败！',
                    message: response.data.msg,
                    type: 'warning',
                  });
                }
              });
            } catch (e) {
              ElNotification({
                title: '失败！',
                message: '出现未知问题，请联系管理员！',
                type: 'error',
              })
            }
          } else {
            ElNotification({
              title: '失败！',
              message: response.data.msg,
              type: 'warning',
            });
          }
        })
      } catch (e) {
        ElNotification({
          title: '失败！',
          message: '出现未知问题，请联系管理员！',
          type: 'error',
        })
      }
    },
    passNum(sn) {
      sn.snStatus = 3;
      this.renewSn(sn);
    },
    callNum(sn) {
      sn.snStatus = 2;
      this.renewSn(sn);
    },
    async renewSn(sn) {
      try {
        await renewSn(sn).then(async (response) => {
          if (response.data.code == 200) {
            ElNotification({
              title: '成功！',
              message: "叫号成功！",
              type: 'success',
            });
            this.fetchAllSn();
          } else {
            ElNotification({
              title: '失败！',
              message: response.data.msg,
              type: 'warning',
            });
          }
        })
      } catch (e) {
        ElNotification({
          title: '失败！',
          message: '出现未知问题，请联系管理员！',
          type: 'error',
        })
      }
    },
    formatTime(timeStr) {
      const appointmentTime = new Date(timeStr);
      const year = appointmentTime.getFullYear();
      const month = String(appointmentTime.getMonth() + 1).padStart(2, '0');
      const day = String(appointmentTime.getDate()).padStart(2, '0');
      const hours = String(appointmentTime.getHours()).padStart(2, '0');
      const minutes = String(appointmentTime.getMinutes()).padStart(2, '0');
      const seconds = String(appointmentTime.getSeconds()).padStart(2, '0');
      return `${year}年${month}月${day}日 ${hours}时${minutes}分${seconds}秒`;
    },
    async fetchAllDrug() {
      const response = await fetchAllDrug();
      this.drugs = response.data.data;
    },
    async fetchAllSn() {
      const response = await fetchAllSn(this.token);
      this.sns = response.data.data;
    }
  }
}
</script>

<style scoped>

</style>
